package me.flyray.bsin.infrastructure.biz.paychannel.joinpay.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Map;

@Slf4j
public class MapUtils {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 通用转换方法：对象 -> MultiValueMap
     */
    public static <T> MultiValueMap<String, String> convertToMap(T obj) {
        if (obj == null) {
            return new LinkedMultiValueMap<>();
        }
        
        try {
            // 直接通过 JSON 转换
            String jsonString = objectMapper.writeValueAsString(obj);
            log.debug("转换的 JSON: {}", jsonString);
            
            Map<String, Object> map = objectMapper.readValue(jsonString, new TypeReference<>() {});
            
            MultiValueMap<String, String> result = new LinkedMultiValueMap<>();
            map.forEach((key, value) -> {
                if (value != null) {
                    // 复杂对象（数组、对象）保持 JSON 格式
                    if (value instanceof Map || value instanceof java.util.List) {
                        try {
                            result.add(key, objectMapper.writeValueAsString(value));
                        } catch (Exception e) {
                            result.add(key, value.toString());
                        }
                    } else {
                        result.add(key, value.toString());
                    }
                }
            });
            
            return result;
            
        } catch (Exception e) {
            log.error("对象转 MultiValueMap 失败: {}", obj.getClass().getSimpleName(), e);
            throw new RuntimeException("转换失败", e);
        }
    }

    /**
     * 转换并排除指定字段
     */
    public static <T> MultiValueMap<String, String> convertToMapExclude(T obj, String... excludeFields) {
        MultiValueMap<String, String> result = convertToMap(obj);
        
        if (excludeFields != null) {
            for (String field : excludeFields) {
                result.remove(field);
            }
        }
        
        return result;
    }

    /**
     * JSON 字符串直接转 MultiValueMap
     */
    public static MultiValueMap<String, String> jsonToMap(String jsonString) {
        try {
            Map<String, Object> map = objectMapper.readValue(jsonString, new TypeReference<>() {});
            
            MultiValueMap<String, String> result = new LinkedMultiValueMap<>();
            map.forEach((key, value) -> {
                if (value != null) {
                    result.add(key, value.toString());
                }
            });
            
            return result;
            
        } catch (Exception e) {
            log.error("JSON 字符串转 MultiValueMap 失败", e);
            throw new RuntimeException("JSON 转换失败", e);
        }
    }
}